package com.shenhao.hpfa.netty.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.shenhao.hpfa.netty.HpfaNettyClient;
import com.shenhao.hpfa.util.JsonFragmentReassembler;
import com.shenhao.hpfa.util.JsonUtil;
import com.shenhao.hpfa.util.LatchHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class ResponseHandler extends SimpleChannelInboundHandler<String> {

    private final HpfaNettyClient client;
    private final String deviceSn;

    public ResponseHandler(HpfaNettyClient client, String deviceSn) {
        this.client = client;
        this.deviceSn = deviceSn;
    }
    
    // 兼容旧版本的构造函数
    public ResponseHandler(HpfaNettyClient client) {
        this(client, "default");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        log.debug("控制器 {} 接收到数据片段: {}", deviceSn, msg);
        
        // 获取通道ID
        String channelId = ctx.channel().id().asLongText();
        
        // 使用JSON片段重组器处理
        List<String> completeJsons = JsonFragmentReassembler.processFragment(channelId, msg);
        
        if (!completeJsons.isEmpty()) {
            for (String completeJson : completeJsons) {
                log.info("控制器 {} 接收到完整JSON: {}", deviceSn, completeJson);
                try {
                    JsonNode root = JsonUtil.getObjectMapper().readTree(completeJson);
                    String mid = root.get("mid").asText();
                    LatchHolder.putResp(mid, completeJson);
                    LatchHolder.countdown(mid);
                } catch (Exception e) {
                    log.error("解析完整JSON出现异常", e);
                }
            }
        } else {
            log.debug("JSON片段接收，等待更多数据...");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("控制器 {} 的处理器发生异常", deviceSn, cause);
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("控制器 {} 成功连接上服务端", deviceSn);
        client.setConnectState(deviceSn, true);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.warn("控制器 {} 已断开连接", deviceSn);
        client.setConnectState(deviceSn, false);
        
        // 清理该通道的JSON片段缓冲区
        String channelId = ctx.channel().id().asLongText();
        JsonFragmentReassembler.clearBuffer(channelId);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 如果是 idle 事件,调用 inactive 方法, 并关闭连接
        if (evt instanceof IdleStateEvent) {
            switch (((IdleStateEvent) evt).state()) {
                case READER_IDLE:
                    log.warn("控制器 {} 读空闲", deviceSn);
                    break;
                case WRITER_IDLE:
                    log.warn("控制器 {} 写空闲", deviceSn);
                    break;
                case ALL_IDLE:
                    log.warn("控制器 {} 读写空闲", deviceSn);
                    break;
            }
            ctx.close();
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}